package icantalk.voip;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * Secondary class used for easier sendig of data
 * trough UDP
 *
 * @author Antonín Brettšnajdr
 */
public class UDPSender extends Thread {

    String str, ip;
    int port;
    long interval;
    boolean run;
    DatagramSocket socket;

    public DatagramSocket getSocket() {
        return socket;
    }

    public void setStr(String str) {
        this.str = str;
    }

    public void send(String s) {
        byte[] data = str.getBytes();
        InetSocketAddress address = new InetSocketAddress(ip, port);

        DatagramPacket packet = null;
        try {
            packet = new DatagramPacket(data, data.length, address);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            socket.send(packet);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public UDPSender(DatagramSocket sock, String ip, int port, String s, long i) {
        super();
        str = s;
        interval = i;
        run = true;
        this.socket = sock;
        this.ip = ip;
        this.port = port;
        this.start();
    }

    public void terminate() {
        run = false;
    }

    @Override
    public void run() {

        while (run) {

            this.send(str);

            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }
}
